#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-sudoers
# REQUIRE: FILESYSTEMS

. /etc/rc.freenas

SUDOERS_FILE="/usr/local/etc/sudoers"

sudoers_start()
{
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	local IFS="|"

	echo > "${SUDOERS_FILE}"
	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "\
	SELECT
		bsdusr_username
	FROM
		account_bsdusers
	WHERE
		bsdusr_sudo = 1
	" | while read -r username
	do
		echo "${username} ALL=(ALL) ALL" >> "${SUDOERS_FILE}"
	done

	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "\
	SELECT
		bsdgrp_group
	FROM
		account_bsdgroups
	WHERE
		bsdgrp_sudo = 1
	" | while read -r group
	do
		echo "%${group} ALL=(ALL) ALL" >> "${SUDOERS_FILE}"
	done

	cat /conf/base/etc/local/sudoers >> "${SUDOERS_FILE}"
}

name="ix-sudoers"
start_cmd='sudoers_start'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
